//
//  GKSearchHistoryController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/20.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit

private let height = GKBookCell.cellSearchSize.height + 60
private let topHeight = CGFloat(40)
class GKSearchHistoryController: BaseTableViewController {
    lazy var searchRealm = BSearchRealm()
    lazy var tableHeadView : UIView = {
        return UIView()
    }()
    lazy var info : GKHomeInfo = {
        return GKHomeInfo()
    }()
    lazy var listData : [BSearch] = {
        return [];
    }()
    lazy var collectionView : UICollectionView = {
        let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout();
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = .horizontal;
        let collectionView : UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout: layout);
        collectionView.dataSource = self;
        collectionView.delegate = self;
        collectionView.showsVerticalScrollIndicator = false;
        collectionView.showsHorizontalScrollIndicator = false;
        collectionView.isScrollEnabled = true;
        collectionView.backgroundColor = UIColor.appxffffff();
        collectionView.backgroundView?.backgroundColor = UIColor.appxffffff();
        return collectionView
    }()
    lazy var searchView : GKSearchTopView = {
        let searchView : GKSearchTopView = GKSearchTopView()
        searchView.textField.delegate = self;
        return searchView;
    }()
    lazy var headView : GKSearchHeadView = {
        let headView : GKSearchHeadView = GKSearchHeadView()
        headView.backgroundColor = UIColor.appxffffff();
        headView.titleLab.text = "历史记录";
        return headView;
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchView.config = { [weak self] (topView) in
            self?.back(animated: false)
        }
        self.searchView.setConfig { (topView) in
            topView.textField.placeholder = "请输入作者、书名"
        }
        self.tableHeadView.backgroundColor = UIColor.appxffffff();
        //self.fd_interactivePopDisabled = true;
        self.fd_prefersNavigationBarHidden = true;
        self.view.addSubview(self.searchView);
        self.searchView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview();
            make.height.equalTo(NAVI_BAR_HIGHT);
        }
        self.tableView.snp.remakeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.searchView.snp.bottom)
            
        }
        self.tableView.backgroundColor = UIColor.appxffffff()
        self.setupRefresh(scrollView: self.tableView, options: .defaults)
        if self.searchView.textField.canBecomeFirstResponder {
            self.searchView.textField.becomeFirstResponder();
        }
        let title = GKSearchHeadView();
        title.titleLab.text = "最热搜索";
        title.deleteBtn.isHidden = true;
        self.tableHeadView.addSubview(title);
        title.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview();
            make.height.equalTo(topHeight);
        }
        self.tableHeadView.addSubview(self.collectionView);
        self.collectionView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview();
            make.top.equalTo(title.snp.bottom);
        }
        self.tableHeadView.isHidden = true;
        self.headView.deleteBtn.rx.tap.bind { [weak self]() in
            self?.deleteAction()
        }.disposed(by: disposeBag)
    }
    @objc func deleteAction(){
        ATAlertView.showAlertView(title: "确定删除所有历史记录", message: "", normals: ["取消"], hights: ["确定"]) { [self] (title , index) in
            if index > 0{
                self.searchRealm.deleteAll()
                self.listData.removeAll();
                self.tableView.reloadData();
//                GKSearchData.deleteKeyWord(datas: self.listData, completion: { (success) in
//                    if success{
//                        self.listData.removeAll();
//                        self.tableView.reloadData();
//                    }
//                })
            }
        }
    }
    func searchTextField(keyWork :String){
        let texts = keyWork.trimmingCharacters(in: .whitespaces);
        self.inseartData(keyWork: texts);
        GKJump.jumpToSearchResult(keyWord: keyWork);
    }
    func inseartData(keyWork :String){
        self.searchRealm.insertData(keyWork)
        self.refreshData(page: 1)
//        GKSearchData.insertKeyWord(keyWord: keyWork) { (success) in
//            if success{
//                self.refreshData(page: 1)
//            }
//        }
    }
    override func refreshData(page: Int) {
       // var list : [ String] = [];
        let group : DispatchGroup = DispatchGroup()
        if page == 1 {
            group.enter();
            ApiMoya.request(target: .homeHot("5a6844aafc84c2b8efaa6b6e")) { json in
                if let info = GKHomeInfo.deserialize(from: json["ranking"].rawString()){
                    self.info = info;
                }
                group.leave()
            } failure: { error in
                group.leave()
            }
        }
//        group.enter();
//        GKSearchData.getKeyWords(page: page, size: NSInteger(30)) { (datas) in
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
//                list = datas;
//                if page == 1{
//                    self.listData.removeAll();
//                }
//                if datas.count > 0{
//                    self.listData.append(contentsOf:datas);
//                }
//                group.leave()
//            }
//
//        }
        group.notify(queue:DispatchQueue.main) {
            if page == 1{
                self.listData.removeAll()
            }
            if let list = self.searchRealm.getDatas(){
                self.listData = list
            }
            self.tableHeadView.isHidden = self.info.books.count == 0
            self.tableHeadView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: self.info.books.count == 0 ? 0.1 :height)
            self.tableView.tableHeaderView = self.tableHeadView
            self.tableView.reloadData()
            self.endRefresh(more: false)
            self.collectionView.reloadData()
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = GKSearchHistoryCell.cellForTableView(tableView: tableView, indexPath: indexPath) ;
        cell.titleLab.text = self.listData[indexPath.row].keyword
        return cell;
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return self.listData.count > 0 ? topHeight : 0.001
    }
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        self.headView.isHidden = self.listData.count == 0;
        return self.headView
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);
        GKJump.jumpToSearchResult(keyWord:self.listData[indexPath.row].keyword);
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true;
    }
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(style: .destructive, title: "删除") { action, view, finish in
            self.searchRealm.deleteData(self.listData[indexPath.row].keyword)
            if self.listData.count > indexPath.row{
                self.listData.remove(at: indexPath.row)
                self.tableView.reloadData();
            }
//            GKSearchData.deleteKeyWord(keyWord: self.listData[indexPath.row], completion: { (success) in
//                if success{
//                    if self.listData.count > indexPath.row{
//                        self.listData.remove(at: indexPath.row)
//                        self.tableView.reloadData();
//                    }
//                }
//            });
        }
        return UISwipeActionsConfiguration(actions: [action])
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent;
    }
    override var refreshVertica: CGFloat{
        return self.info.listData.count > 0 ? height/2 : 0.001
    }
}
extension GKSearchHistoryController :UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.info.books.count
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0;
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0;
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return GKBookCell.inset
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return GKBookCell.cellSearchSize
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell  = GKBookCell.cellForCollectionView(collectionView: collectionView, indexPath: indexPath)
        cell.model = self.info.books[indexPath.row]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.info.books[indexPath.row]
        GKJump.jumpToDetail(bookId: model.bookId)
    }
}
extension GKSearchHistoryController :UITextFieldDelegate{
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.text?.count == 0 {
            textField.resignFirstResponder();
            return false;
        }
        self.searchTextField(keyWork:textField.text!);
        return true;
    }
}
